package com.pearadmin.pro.common.utils.upload;

import com.pearadmin.pro.common.utils.IdUtils;
import com.pearadmin.pro.common.utils.upload.MimeTypeUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Date;

public class FileUploadUtils {


    /**
     * 默认上传的地址
     */
    public static final String defaultBaseDir = "D:/resource/";
//    public static final String defaultBaseDir = "/mnt/apps/xiaojizonghepingtai/resource";
   private static final String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");



    public static final String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        //上传文件
        String fileName = extractFilename(file); //获取文件名，带后缀
        File folderPath = new File(defaultBaseDir + "/" + format);
        //查询文件夹是否存在
        if (!folderPath.exists() && !folderPath.isDirectory()) {
            folderPath.mkdirs();//建立多级子目录
            System.out.println("目录不存在，创建新文件夹");
        }

        File filePath = new File(defaultBaseDir + "/" + format + "/" + fileName);
        //根据该文件名删除重复文件
        replaceFile(filePath);
        try {
            file.transferTo(filePath);//将上传的文件写到服务器上指定的文件路径
            System.out.println("上传成功！");
        } catch (IOException e) {
            throw new IOException(e.getMessage());
        }
        return "/resource" + "/" +format + "/" + fileName;
    }


    private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = IdUtils.fastUUID() + "." + extension;
        return fileName;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    // 删除文件
    public static void replaceFile(File file) {
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("文件不存在");
        }

    }
}
